package com.lzs.kunei.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.*;
import com.lzs.kucun.service.StockService;
import com.lzs.kunei.feign.FeignRuku;
import com.lzs.kunei.service.PutonService;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 上架 前端控制器
 * </p>
 *
 * @author wpy
 * @since 2020-11-24
 */
@RestController
@ApiModel(value = "上架")
@RequestMapping("/kunei/puton")
public class PutonController {
    @Autowired
    private PutonService putonService;
    @Autowired
    private StockService stockService;
    @Autowired
    private FeignRuku feignRuku;
    @PostMapping("/selectPutonPage/{current}/{size}")
    public R selectPutonPage(@PathVariable Integer current, @PathVariable Integer size, @RequestBody Puton puton,HttpServletRequest request){
        Page<Puton> putonPage=null;
        String warehouseId = request.getHeader("warehouseId");
        //System.out.println(warehouseId);
        String[] warehouseid = warehouseId.split(",");


        try {
           putonPage = putonService.selectPutonPage(current, size, puton,warehouseid);

            return R.ok().message("查询成功").data("putonPage",putonPage);
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("查询出错").data("putonPage",putonPage);
        }
    }
    @ApiOperation(value = "上架审核")
    @PostMapping("/updateAudit")
    public R updateAudit(@RequestBody List<Puton> list, HttpServletRequest request) {
        String token=request.getHeader("token");
        Long userid= JwtUtils.getMemberIdByJwtToken(token);
        User user=stockService.selectUser(userid);
        String name = user.getName();
        int j=1;
        for (int i = 0; i < list.size(); i++) {
            Puton puton = list.get(i);
            if (!puton.getState().equals("1")){
                return R.error().message("存在通过审核的订单,或者不可用的订单,请重新选择");
            }
        }
        try {
            for (int i = 0; i < list.size(); i++) {
                Puton puton = list.get(i);
                QueryWrapper<Puton> putonQueryWrapper = new QueryWrapper<>();
                putonQueryWrapper.eq("id", puton.getId());
                Puton puton1 = new Puton();

                puton1.setState("2");
                puton1.setAudittime(new Date());
                puton1.setAuditid(userid);
                puton1.setAuditor(name);
                puton1.setUpdateid(userid);
                puton1.setUpdator(name);
                Integer qty = puton.getQty();
                String locatorcode = puton.getLocatorcode();
                String oldlocatorcode = puton.getOldlocatorcode();
                String commoditybar = puton.getCommoditybar();
                Long warehouseid = puton.getWarehouseid();
                R r = stockService.updateLqtyQuantity(oldlocatorcode,commoditybar,warehouseid,qty);
                if (!r.getSuccess()){
                    j=0;
                    continue;
                }
                if (r.getSuccess()) {
                    putonService.update(puton1, putonQueryWrapper);
                    Stock stock = new Stock();
                    stock.setUqty(puton.getQty());
                    stock.setCqty(puton.getQty());
                    stock.setLqty(0);
                    BeanUtils.copyProperties(puton, stock);
                    if (!stockService.selectIsExit(locatorcode,commoditybar,warehouseid)){
                        stock.setCreator(name);
                        stock.setCreateid(userid);
                        Locator locator = stockService.selectLocator(locatorcode);
                        stock.setLocatorname(locator.getName());
                        stock.setLocatorid(locator.getId());
                        stockService.save(stock);
                    }else {
                        stockService.updateAllQuantity(locatorcode,commoditybar,warehouseid,qty);
                    };//修改库存管理的可用和总数量

                }
            }
            if (j==1){
                return R.ok().message("全部审核成功");
            }else {
                return R.ok().message("存在未审核成功的订单");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("审核出错");
        }

    }
    @ApiOperation(value = "取消审核")
    @PostMapping("/cancelAudit")
    public R cancelAudit(@RequestBody List<Puton> list,HttpServletRequest request){
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            int j=1;
            for (int i = 0; i < list.size(); i++) {
                Puton puton = list.get(i);
                if (!puton.getState().equals("2")){
                    return R.error().message("存在未审核的订单或不可用的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Puton puton = list.get(i);
                QueryWrapper<Puton> putonQueryWrapper = new QueryWrapper<>();
                putonQueryWrapper.eq("id", puton.getId());
                Puton puton1 = new Puton();
                puton1.setState("3");
                puton1.setUpdateid(userid);
                puton1.setUpdator(name);
                Integer qty = puton.getQty();
                String locatorcode = puton.getLocatorcode();
                String oldlocatorcode = puton.getOldlocatorcode();
                String commoditybar = puton.getCommoditybar();
                Long warehouseid = puton.getWarehouseid();
                R r = stockService.reduceQuantity(locatorcode,commoditybar,warehouseid,qty);
                if (!r.getSuccess()){
                    j=0;
                    continue;
                }
                if (r.getSuccess()) {
                    putonService.update(puton1,putonQueryWrapper);
                    stockService.updateAllQuantity(oldlocatorcode,commoditybar,warehouseid,qty);
                    };
                }
            if (j==1){
                return R.ok().message("全部取消审核成功");
            }else {
                return R.ok().message("存在未取消审核成功的订单");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("取消审核出错");
        }
    }

    /**
     * 数量判断前台输入与入库区的数量进行判断
     * @param
     * @return
     */
    @ApiOperation(value = "上架添加到上架管理")
    @PostMapping("addPuton")
    public R addPuton(@RequestBody Puton moveEntry,HttpServletRequest request){
        System.out.println(moveEntry.toString());
        String token=request.getHeader("token");
        Long userid= JwtUtils.getMemberIdByJwtToken(token);
        User user=stockService.selectUser(userid);
        String name = user.getName();
        String locatorcode = moveEntry.getLocatorcode();
        String oldLocatorcode = moveEntry.getOldlocatorcode();
        Long warehouseid = moveEntry.getWarehouseid();
        Integer qty = moveEntry.getQty();
        String commoditybar = moveEntry.getCommoditybar();
        try {
            R r = stockService.updateUqtyQuantity(oldLocatorcode, commoditybar, warehouseid, qty);
            if (!r.getSuccess()){
            return R.error().message("数量不足,上架失败");
        }
            Locator oldlocator = stockService.selectLocator(oldLocatorcode);
            Locator locator = stockService.selectLocator(locatorcode);
            Commodity commodity = stockService.selectCommodity(commoditybar);
            moveEntry.setLocatorid(locator.getId());
            moveEntry.setLocatorname(locator.getName());
            moveEntry.setOldlocatorid(oldlocator.getId());
            moveEntry.setOldlocatorname(oldlocator.getName());
            moveEntry.setCommodityid(commodity.getId());
            moveEntry.setCommodityname(commodity.getName());
            moveEntry.setState("1");
            moveEntry.setCreateid(userid);
            moveEntry.setCreator(name);
            putonService.save(moveEntry);
            return R.ok().message("上架成功");
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("上架失败");
        }

    }

    @ApiOperation("上架的下拉")
    @PostMapping("/selectCom")
    public R selectCom(@RequestBody Puton puton){
        Long warehouseid = puton.getWarehouseid();
        System.out.println(warehouseid);
        String commoditybar = puton.getCommoditybar();
        List<Stock> locators = stockService.selectStockInfo(warehouseid, "2");
        QueryWrapper<Stock> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("warehouseid",warehouseid);
        Set set=new HashSet();
        Set locators1=new HashSet();
        locators1.add("0");
        List<Stock> list = stockService.list(queryWrapper);

      for (int i = 0; i <locators.size() ; i++) {
           locators1.add(locators.get(i).getLocatorcode());
       }
        System.out.println(locators1.toString());
        QueryWrapper<Stock> queryWrapper1=new QueryWrapper<>();
      queryWrapper1.in("locatorcode",locators1);
      queryWrapper.eq("warehouseid",warehouseid);
        List<Stock> list2 = stockService.list(queryWrapper1);
        for (int i = 0; i <list2.size(); i++) {
            set.add(list2.get(i).getCommoditybar());
        }
        if (StringUtils.isNotEmpty(commoditybar)){
            queryWrapper1.eq("commoditybar",commoditybar);
        }
        List<Stock> list1 = stockService.list(queryWrapper1);
        System.out.println(set);
        return R.ok().data("commoditybars",set).data("oldlocatorcodes",list1);

    }


}

